<script setup lang="ts">
import { reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';

import { $t } from '@vben/locales';

import {
  ElButton,
  ElCard,
  ElDatePicker,
  ElForm,
  ElFormItem,
  ElMessage,
  ElTable,
  ElTableColumn,
} from 'element-plus';

import { getSupplierStockListApi } from '#/api';
import CollapsibleCard from '#/components/collapsibleCard.vue';
import CurrentDateTime from '#/components/currentDateTime.vue';
import { getCommonShortcuts } from '#/utils';
import { convertToSingleImageAndPrint } from '#/utils/convertAndSplitImage';

const { locale } = useI18n();
const router = useRouter();
const shortcuts = ref(getCommonShortcuts());

watch(locale, () => {
  shortcuts.value = getCommonShortcuts();
});
const submitForm: any = reactive({
  timeRange: [], // 统计日期
});

const lastCollectDate = ref<any>(null);

const onSubmit = async () => {
  if (!submitForm.timeRange[0] || !submitForm.timeRange[1]) {
    ElMessage.warning('请选择统计日期！');
    return;
  }
  const params = {
    startDate: submitForm.timeRange[0],
    endDate: submitForm.timeRange[1],
  };
  const { data, systemLastDate } = await getSupplierStockListApi(params);
  lastCollectDate.value = systemLastDate;
  const nfArr = new Set(['publisherName']);
  data.forEach((item: any) => {
    for (const key in item) {
      if (!nfArr.has(key) && !key.includes('Num')) {
        item[key] =
          String(item[key]) === 'infinity' || item[key] === 'NaN'
            ? '-'
            : item?.[key]?.toFixed(2) || '-';
      }
    }
  });

  tableData.value = data;
};

// 供应商点击跳转到明细页面
const supplierClick = (publisherName: string) => {
  const params = {
    timeRange: submitForm.timeRange,
    supplier: publisherName,
  };

  router.push({
    path: '/report/supplierStockDetail',
    query: {
      k: JSON.stringify(params),
    },
  });
};

async function printSection() {
  const w = document
    .querySelector('#printContent2')
    ?.getBoundingClientRect()?.width;
  await convertToSingleImageAndPrint('#printContent2', `${w}px`);
}

const tableData = ref<any>([]);

const decimalFields = new Set([
  'jhCost',
  'jhMayang',
  'lastCost',
  'lastMayang',
  'pdCost',
  'pdMayang',
  'qcCost',
  'qcMayang',
  'thCost',
  'thMayang',
  'xsCost',
  'xsMayang',
  'xsShiyang',
]);
const numberFields = new Set([
  'jhNum',
  'lastNum',
  'pdNum',
  'pzNum',
  'qcNum',
  'thNum',
  'xsNum',
]);
const sortBy = ref('');
const sortOrder = ref('');
function formatNumber(val: any) {
  if (val === '-' || val === undefined || val === null) return '-';
  const num = Number(val);
  if (Number.isNaN(num) || !Number.isFinite(num)) return '-';
  return num.toFixed(2);
}
const handleSortChange = ({ prop, order }: { order: string; prop: string }) => {
  sortBy.value = prop;
  sortOrder.value = order;
  if (!order) return;
  if (prop === 'publisherName') {
    tableData.value.sort((a: any, b: any) =>
      order === 'ascending'
        ? String(a[prop]).localeCompare(String(b[prop]))
        : String(b[prop]).localeCompare(String(a[prop])),
    );
  } else if (numberFields.has(prop)) {
    tableData.value.sort((a: any, b: any) => {
      const aVal = Number(a[prop]);
      const bVal = Number(b[prop]);
      if (Number.isNaN(aVal) || !Number.isFinite(aVal)) return 1;
      if (Number.isNaN(bVal) || !Number.isFinite(bVal)) return -1;
      return order === 'ascending' ? aVal - bVal : bVal - aVal;
    });
  } else if (decimalFields.has(prop)) {
    tableData.value.sort((a: any, b: any) => {
      const aVal = Number(a[prop]);
      const bVal = Number(b[prop]);
      if (Number.isNaN(aVal) || !Number.isFinite(aVal)) return 1;
      if (Number.isNaN(bVal) || !Number.isFinite(bVal)) return -1;
      return order === 'ascending' ? aVal - bVal : bVal - aVal;
    });
  }
};
</script>

<template>
  <!-- 使用 mx-auto 实现左右外边距自动，justify-center 让子元素水平居中 -->
  <div
    class="relative mx-auto flex items-center justify-center space-x-8"
    style="height: calc(100vh - 88px)"
  >
    <CollapsibleCard>
      <ElForm :model="submitForm" label-position="top" @keyup.enter="onSubmit">
        <ElFormItem :label="$t('views.common.collectDate')">
          <ElDatePicker
            v-model="submitForm.timeRange"
            type="daterange"
            date-format="yyyy-MM-DD"
            value-format="YYYY-MM-DD"
            unlink-panels
            range-separator="-"
            :start-placeholder="$t('views.common.startDate')"
            :end-placeholder="$t('views.common.endDate')"
            :shortcuts="shortcuts"
          />
        </ElFormItem>
        <ElFormItem>
          <div class="flex w-full justify-center">
            <ElButton type="primary" @click="onSubmit">
              {{ $t('views.common.filter') }}
            </ElButton>
            <ElButton @click="printSection"> 打印 </ElButton>
          </div>
        </ElFormItem>
      </ElForm>
    </CollapsibleCard>
    <ElCard class="!ml-1 h-full flex-1 !overflow-auto" id="printContent2">
      <h2 class="my-2 flex items-center justify-center text-base font-bold">
        {{ `${$t('page.report.supplierStockList')}` }}
      </h2>
      <div class="flex justify-end text-xs">
        <div class="mr-4">最后数据时间：{{ lastCollectDate }}</div>
        <div class="mr-4">
          {{ $t('views.common.statisticalDate') }}：<span
            v-if="submitForm.timeRange[0] && submitForm.timeRange[1]"
          >
            {{ `${submitForm.timeRange[0]}` }} -
            {{ `${submitForm.timeRange[1]}` }}
          </span>
        </div>
        <CurrentDateTime />
      </div>
      <ElTable
        :data="tableData"
        border
        table-layout="auto"
        class="w-full"
        @sort-change="handleSortChange"
      >
        <ElTableColumn
          header-align="center"
          min-width="120"
          :label="$t('views.common.supplier')"
          prop="publisherName"
          sortable="custom"
        >
          <template #default="scope">
            <div
              class="text-align-right hover-supplier cursor-pointer !justify-start"
              @click="supplierClick(scope.row.publisherName)"
            >
              {{ scope.row.publisherName }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          align="right"
          label="总品种"
          width="95"
          prop="pzNum"
          sortable="custom"
        >
          <template #default="scope">
            {{ scope.row.pzNum }}
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          align="right"
          width="105"
          label="期初数量"
          prop="qcNum"
          sortable="custom"
        >
          <template #default="scope">
            {{ scope.row.qcNum }}
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          align="right"
          label="期初码洋"
          prop="qcMayang"
          sortable="custom"
        >
          <template #default="scope">
            {{ formatNumber(scope.row.qcMayang) }}
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          align="right"
          label="期初成本"
          prop="qcCost"
          sortable="custom"
        >
          <template #default="scope">
            {{ formatNumber(scope.row.qcCost) }}
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          align="right"
          label="进货数"
          width="95"
          prop="jhNum"
          sortable="custom"
        >
          <template #default="scope">
            {{ scope.row.jhNum }}
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          align="right"
          label="进货码洋"
          prop="jhMayang"
          sortable="custom"
        >
          <template #default="scope">
            {{ formatNumber(scope.row.jhMayang) }}
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          align="right"
          label="进货成本"
          prop="jhCost"
          sortable="custom"
        >
          <template #default="scope">
            {{ formatNumber(scope.row.jhCost) }}
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          align="right"
          label="退货数"
          width="95"
          prop="thNum"
          sortable="custom"
        >
          <template #default="scope">
            {{ scope.row.thNum }}
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          align="right"
          label="退货码洋"
          prop="thMayang"
          sortable="custom"
        >
          <template #default="scope">
            {{ formatNumber(scope.row.thMayang) }}
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          align="right"
          label="退货成本"
          prop="thCost"
          sortable="custom"
        >
          <template #default="scope">
            {{ formatNumber(scope.row.thCost) }}
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          align="right"
          label="盘点数"
          width="95"
          prop="pdNum"
          sortable="custom"
        >
          <template #default="scope">
            {{ scope.row.pdNum }}
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          align="right"
          label="盘点码洋"
          prop="pdMayang"
          sortable="custom"
        >
          <template #default="scope">
            {{ formatNumber(scope.row.pdMayang) }}
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          align="right"
          label="盘点成本"
          prop="pdCost"
          sortable="custom"
        >
          <template #default="scope">
            {{ formatNumber(scope.row.pdCost) }}
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          align="right"
          label="销售数"
          width="95"
          prop="xsNum"
          sortable="custom"
        >
          <template #default="scope">
            {{ scope.row.xsNum }}
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          align="right"
          label="销售码洋"
          prop="xsMayang"
          sortable="custom"
        >
          <template #default="scope">
            {{ formatNumber(scope.row.xsMayang) }}
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          align="right"
          label="销售成本"
          prop="xsCost"
          sortable="custom"
        >
          <template #default="scope">
            {{ formatNumber(scope.row.xsCost) }}
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          align="right"
          label="销售实洋"
          prop="xsShiyang"
          sortable="custom"
        >
          <template #default="scope">
            {{ formatNumber(scope.row.xsShiyang) }}
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          align="right"
          label="期末数量"
          width="105"
          prop="lastNum"
          sortable="custom"
        >
          <template #default="scope">
            {{ scope.row.lastNum }}
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          align="right"
          label="期末码洋"
          prop="lastMayang"
          sortable="custom"
        >
          <template #default="scope">
            {{ formatNumber(scope.row.lastMayang) }}
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          align="right"
          label="期末成本"
          prop="lastCost"
          sortable="custom"
        >
          <template #default="scope">
            {{ formatNumber(scope.row.lastCost) }}
          </template>
        </ElTableColumn>
      </ElTable>
    </ElCard>
  </div>
</template>

<style scoped>
:deep(.el-table .cell .el-table__cell) {
  padding: 0 3px !important;
  white-space: nowrap;
}

:deep(.el-table__cell) {
  padding: 3px 0 !important;
  white-space: nowrap;
}

.hover-supplier:hover {
  color: hsl(var(--primary, 210 100% 50%));
  text-decoration: underline;
  text-underline-offset: 2px; /* 设置下划线距离文字的距离 */
}
</style>
